package com.gewu.teday

import android.view.LayoutInflater
import android.view.MenuItem
import android.view.View
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentStatePagerAdapter
import com.gewu.teday.activity.BaseActivity
import com.gewu.teday.adapter.MainAdapter
import com.gewu.teday.fragmnet.MineFragment
import com.google.android.material.bottomnavigation.BottomNavigationItemView
import com.google.android.material.bottomnavigation.BottomNavigationMenuView
import com.google.android.material.bottomnavigation.BottomNavigationView
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : BaseActivity(), BottomNavigationView.OnNavigationItemSelectedListener,
    MineFragment.showNums {

    private var fragmentList: ArrayList<Fragment>? = null

    override fun getLayout(): Int = R.layout.activity_main

    override fun initView() {
        fragmentList = ArrayList()
        val mineFragment = MineFragment()
        fragmentList!!.add(mineFragment)
        navigation.setOnNavigationItemSelectedListener(this)
        content.setNoScroll(true)
        mineFragment.setNums(this)

        val supportFragmentManager = supportFragmentManager
        content.adapter = MainAdapter(fragmentList!!, supportFragmentManager,
            FragmentStatePagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT)

        content.currentItem = 3
        navigation.selectedItemId = R.id.mine_ic

        val menuItem = navigation.menu
        for (i in 0 until menuItem.size()) {
            menuItem.getItem(i).isEnabled = false
        }
    }

    override fun initData() {
    }

    override fun onNavigationItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.mine_ic -> {
                content.currentItem = 3
            }
        }
        return true
    }

    private var badge: View? = null

    override fun nums(num: Int) {
        val menuView = navigation.getChildAt(0) as BottomNavigationMenuView
        val tab = menuView.getChildAt(menuView.childCount - 1);
        if (tab != null) {
            val itemView = tab as BottomNavigationItemView
            if (badge==null){
                badge = LayoutInflater.from(this).inflate(R.layout.jiao_num, itemView,false);
                itemView.addView(badge);
            }
            val nums = badge?.findViewById<TextView>(R.id.nums)
            nums!!.text = num.toString()
            nums.visibility = View.VISIBLE
            if (num.toInt() == 0) {
                nums.visibility = View.GONE
            } else if (num.toInt() > 99) {
                nums.text = "99+"
            }
        }
    }
}